import { setToken as _setToken, getToken, removeToken } from "@/utils";
import { createSlice } from "@reduxjs/toolkit";
import { getUserInfoAPI, LoginAPI } from "@/apis/user";

const userStore = createSlice({
    name : 'user',
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    reducers: {
        setToken(state, action){
            state.token = action.payload
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo = action.payload
        },
        clearUserInfo(state){
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
})
const { setToken, setUserInfo,clearUserInfo } = userStore.actions
const userReducers = userStore.reducer

// 编写我们的异步代码,登录
const fetchLogin = (loginForm) => {
    return async(dispatch) => {
       const res = await LoginAPI(loginForm)
       dispatch(setToken(res.data.token))
    }
}
// 获取用户信息
const fetchUserInfo = () => {
    return async(dispatch) => {
        const res = await getUserInfoAPI()
        dispatch(setUserInfo(res.data))
    }
}
export default userReducers
export {setToken, fetchLogin, fetchUserInfo, clearUserInfo}